package com.nbicc.module.interceptor;

import com.nbicc.common.ResponseObj;
import com.nbicc.common.utils.AuthcUserUtil;
import com.nbicc.parent.interceptor.BaseInterceptorRegulation;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by li on 17/12/25.
 * 登陆校验
 */
@Component
public class MyShiroInterceptor extends BaseInterceptorRegulation {

    public MyShiroInterceptor() {
        this.isenabled = true;
    }

    @Override
    public Set<String> getIncludePatterns() {
        Set<String> includePatterns = new HashSet<String>();
        includePatterns.add("/**");
        return includePatterns;
    }

    @Override
    public Set<String> getExcludePatterns() {
        Set<String> includePatterns = new HashSet<String>();

        //swagger address
        includePatterns.add("/v2/api-docs");
        includePatterns.add("/swagger-resources");
        includePatterns.add("/configuration/security");
        includePatterns.add("/configuration/ui");
        //swagger address

        includePatterns.add("/error");
        includePatterns.add("/myError");
        includePatterns.add("/login");
        includePatterns.add("/anon/**");
        includePatterns.add("/");
        return includePatterns;
    }

    /**
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o     @Controller注解下的整个方法名
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(
            HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse,
            Object o) throws Exception {
        if (AuthcUserUtil.isLogin()){
            return true;
        }
        httpServletRequest.setAttribute("result",
                ResponseObj.UNAUTHORIZED
                        .setError("请先登陆").setMessage("此链接不允许匿名访问"));
        httpServletRequest.getRequestDispatcher("/myError").forward(httpServletRequest , httpServletResponse);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
